package com.pocketsweet.ui;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Text;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.pocketsweet.R;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLContext;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLUserLike;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.AutoListView;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.AutoListView.OnLoadListener;
import com.pocketsweet.ui.uilib.AutoListView.OnRefreshListener;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.adapter.FollowListAdapter;
import com.pocketsweet.utils.ShareReferanceUtils;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_follow)
public class NewFollow extends BaseActivity implements OnRefreshListener,
		OnLoadListener, OnItemClickListener {

	@ViewInject(R.id.followedListview)
	private static AutoListView followedListview;

	@ViewInject(R.id.mainHeader)
	private static HeaderLayout header;

	@ViewInject(R.id.linBlank)
	private static LinearLayout linBlank;

	@ViewInject(R.id.tvBlankBg)
	private static TextView tvBlankBg;

	@ViewInject(R.id.tvBlankNoLove)
	private static TextView tvBlankNoLove;

	public static LoadingDailog loading;
	private FollowListAdapter followListAdapter;
	private List<MLUserLike> userLikeList = new ArrayList<MLUserLike>();
	private Context ctx;
	public static final int BEGIN_TO_LOADING = -1;
	private int skipDataCount = 0; // 忽略前N个对象
	public static final int MORE_DATA_MAX_COUNT = 20; // 每页10个对象
	private boolean isUpdateList = false; // 是否刷新列表

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		ctx = this;
		followListAdapter = new FollowListAdapter(NewFollow.this, userLikeList);
		followedListview = (AutoListView) findViewById(R.id.followedListview);
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		linBlank = (LinearLayout) findViewById(R.id.linBlank);
		followedListview.setAdapter(followListAdapter);
		followedListview.setPageSize(MORE_DATA_MAX_COUNT);
		followedListview.setOnRefreshListener(this);
		followedListview.setOnLoadListener(this);
		followedListview.setOnItemClickListener(this);
		setHeaderFunction();
		getFollowedList(AutoListView.REFRESH);
	}

	private void clear() {
		ShareReferanceUtils unreadInviteCount = new ShareReferanceUtils(
				MLApplication.getContext(), "UnreadLiker_"
						+ UserService.getCurrentUserId());
		unreadInviteCount.setIntValue("count", 0);
	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setRightText("");
		header.setMiddleText("喜欢我的人");
		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				NewFollow.this.finish();
			}
		});
	}

	private void getFollowedList(final int what) {
		loading = ToolKits.createLoadingDialog(NewFollow.this, "提交中..");
		loading.setText("正在获取中");
		linBlank.setVisibility(View.GONE);
		if (what != BEGIN_TO_LOADING) {
			isUpdateList = true; // 如果不是首次加载数据，则该动作为刷新
		} else {
			followedListview.setRefreshData(); // 初始化显示loading动态图片
		}
		if (userLikeList == null || userLikeList.size() <= 0 || isUpdateList) { // userList为空或者动作为下拉刷新、往下加载时请求leanCloud

			AVQuery<MLUserLike> querys = new AVQuery<MLUserLike>("MLUserLike");
			skipDataCount = skipDataCount + MORE_DATA_MAX_COUNT; // 往下加载时忽略前一页
			if (what != AutoListView.LOAD) {
				skipDataCount = 0; // 刷新时不用忽略前面对象
			}
			querys.whereEqualTo("likeUser", UserService.getCurrentUser());
			querys.include("user");
			querys.orderByDescending("createdAt");
			querys.setSkip(skipDataCount); // 忽略前N个
			querys.limit(MORE_DATA_MAX_COUNT); // 设置每页对象个数
			querys.findInBackground(new FindCallback<MLUserLike>() {

				@Override
				public void done(List<MLUserLike> users, AVException e) {
					if (e == null) {
						if (users.size() > 0) {
							linBlank.setVisibility(View.GONE);
							switch (what) {
							case AutoListView.REFRESH: // 下拉刷新时直接重新获取数据
								clear(); // 清除红点
								userLikeList = users;
								followedListview.onRefreshComplete();
								// onLineListAdapter.setDatas(userList);
								break;
							case AutoListView.LOAD: // 加载更多时把新获取的数据添加到list列表
								followedListview.onLoadComplete();
								userLikeList.addAll(users);
								break;
							case BEGIN_TO_LOADING: // Application无数据时首次加载，即重新获取数据
								userLikeList = users;
								followedListview.onRefreshComplete();
								// onLineListAdapter.setDatas(userList);
								break;
							}
							followedListview.setResultSize(userLikeList.size());
							followListAdapter.setDatas(userLikeList);
							followListAdapter.notifyDataSetChanged();
							isUpdateList = false; // 刷新完毕，设为false
						} else if (users.size() == 0) {
							linBlank.setVisibility(View.VISIBLE);
							if (what != AutoListView.LOAD) {
								clear();
								tvBlankBg
										.setBackgroundResource(R.drawable.no_follower);
								tvBlankNoLove.setText(getResources().getString(
										R.string.blank_no_follower));
								linBlank.setVisibility(View.VISIBLE);
							}
							followedListview.setNoData();
						}
					} else {
						followedListview.setNoData();
						if (userLikeList.size() <= 0) {
							linBlank.setVisibility(View.VISIBLE);
							tvBlankBg
									.setBackgroundResource(R.drawable.network_error);
							tvBlankNoLove.setText(getResources().getString(
									R.string.blank_network_error));
							linBlank.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View arg0) {
									getFollowedList(BEGIN_TO_LOADING);
								}
							});
						}else{
							ToolKits.toast(NewFollow.this, "网络错误");
						}
					}
				}

			});
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if (position - 1 < 0 || followListAdapter.getCount() <= 0) {
			return;
		}
		MLUserLike selectUser = (MLUserLike) followListAdapter
				.getItem(position - 1);
		String selectedUserId = selectUser.getUser().getObjectId();
		Intent intent = new Intent(NewFollow.this, Profile.class);
		intent.putExtra("userId", selectedUserId);
		intent.putExtra("nickname", selectUser.getUser().getNickname());
		startActivity(intent);

	}

	@Override
	public void onLoad() {
		getFollowedList(AutoListView.LOAD);

	}

	@Override
	public void onRefresh() {
		getFollowedList(AutoListView.REFRESH);
		followedListview.setOnRefreshListener(this);

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

}
